<template>
  <div class="codemirror-editor" ref="containerRef"></div>
</template>

<script lang="ts">
import {defineComponent, onMounted, shallowRef} from 'vue';
import {FormulaEditor, createExtensions, createVariablePlugin} from "@formula/editor";

export default defineComponent({
  name: "FormulaEditorDemo",
  setup() {

    const containerRef = shallowRef<HTMLDivElement>();

    const variableExtension = createVariablePlugin(
        [
          {label: '用户', value: 'user', type: 'object', category: 'field'},
          {label: '用户.名称', value: 'user.name', type: 'string', category: 'field'},
          {label: '用户.年龄', value: 'user.age', type: 'number', category: 'field'},
          {label: '用户.组织', value: 'user.org', type: 'number', category: 'field'},
          {label: '用户.组织.名称', value: 'user.org.name', type: 'text', category: 'field'},
        ],
        /{{(.+?)\}\}/g
    )

    const instance = new FormulaEditor(containerRef, {
      extensions: [...createExtensions({
        keywords: ['name', 'age'],
        functions: ['SUM', 'PLUS', 'ADD'],
        variables: [
          {label: '用户', value: 'user', type: 'object', category: 'field'},
          {label: '用户.名称', value: 'user.name', type: 'string', category: 'field'},
          {label: '用户.年龄', value: 'user.age', type: 'number', category: 'field'},
          {label: '用户.组织', value: 'user.org', type: 'number', category: 'field'},
          {label: '用户.组织.名称', value: 'user.org.name', type: 'text', category: 'field'},
        ],
        hints: [
          {label: '用户', value: '{user}', type: 'variable', detail: '用户',
          children: [
            {label: '名称', value: '{user.name}', type: 'text', detail: '用户的名称'},
            {label: '年龄', value: '{user.age}', type: 'variable', detail: '用户的年龄, number类型'},
            {label: '组织', value: '{user.org}', type: 'class', detail: '用户的组件',
              children: [
                {label: '名称', value: '{user.org.name}', type: 'text', detail: '组件名称'},
              ]
            },
          ]
          },
        ]
      }), variableExtension]
    });

    onMounted(() => {
      console.error(instance, instance.getValue())
      setTimeout(() => {
        instance.setValue('啊实打实发货埃松方哈怂发货叫阿三的法门寺发货 age SUM() name {user} {user.age}');
        console.error(instance.getValue())
      }, 3000)
    })

    return {
      containerRef
    }
  }
})
</script>

<style scoped>
.codemirror-editor {
  text-align: left;
  width: 500px;
  height: 500px;
}
</style>
